package org.topteam.controller.demo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.topteam.controller.DefaultCustomDateEditor;
import org.topteam.domain.demo.Todo;
import org.topteam.service.demo.ITodoService;
import org.topteam.ui.model.EasyDataTableModel;

@Controller
@RequestMapping("/todo")
public class TodoController {

	@Autowired
	private ITodoService todoService;

	@RequestMapping("/list.action")
	public String listPage() {
		return "/demo/TodoList";
	}
	
	@RequestMapping("/addPage.action")
	public String addPage(){
		return "/demo/AddPage";
	}

	@RequestMapping("/todoList.action")
	@ResponseBody
	public EasyDataTableModel<Todo> todoList(HttpServletRequest request) {
		EasyDataTableModel<Todo> model = new EasyDataTableModel<Todo>(request) {

			@Override
			public List<Todo> fechData(int page, int size) throws Exception {
				List<Todo> data = todoService.getTodos(page, size);
				this.setTotal(todoService.getTodoCount());
				return data;
			}
		};
		return model;
	}
	
	@RequestMapping("/saveTodo.action")
	@ResponseBody
	public Todo saveTodo(Todo todo) throws Exception{
		todo.setTodoId(UUID.randomUUID().toString());
		todoService.saveTodo(todo);
		return todo;
	}
	
	@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new DefaultCustomDateEditor(
                dateFormat, true));
    }
}
